<template>
  <main class="content">
    <section class="section">
      <div class="section-header">
        <div class="title-wrapper">
          <h2>能积微者速成</h2>
          <span class="subtitle">开始你的学习之旅</span>
        </div>
        <el-button type="primary" @click="showCreateDialog" class="create-button">
          <el-icon class="el-icon">
            <Plus />
          </el-icon>
          <span class="button-text">新建卡片库</span>
        </el-button>
      </div>
    </section>

    <section class="section learning-content">
      <el-tree
        :data="treeData"
        :props="defaultProps"
        node-key="id"
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
        class="learning-tree"
      >
        <template #default="{ node, data }">
          <div class="custom-tree-node" @click.stop="handleNodeClick(data, node)">
            <span class="node-title">{{ node.label }}</span>
            <span class="node-stats">
              <span class="stat-item">
                <span class="stat-label">新卡片</span>
                <span class="stat-value">{{ calculateNodeStats(data, 'newCards') }}</span>
              </span>
              <span class="stat-item">
                <span class="stat-label">卡片数量</span>
                <span class="stat-value">{{ calculateNodeStats(data, 'toReview') }}</span>
              </span>
              <span class="stat-item">
                <span class="stat-label">复习次数</span>
                <span class="stat-value">{{ calculateNodeStats(data, 'studiedPercentage') }}</span>
              </span>
            </span>
          </div>
        </template>
      </el-tree>
    </section>

    <el-dialog
      title="新建卡片库"
      v-model="dialogVisible"
      :width="isMobile ? '90%' : '500px'"
      :close-on-click-modal="false"
      class="create-dialog"
    >
      <el-form :model="newLibrary" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="卡片库名称" prop="title">
          <el-input v-model="newLibrary.title" placeholder="请输入卡片库名称"></el-input>
        </el-form-item>
        <el-form-item label="父级节点" prop="parentId">
          <el-tree-select
            v-model="newLibrary.parentId"
            :data="treeData"
            :props="defaultProps"
            placeholder="请选择或输入父级节点"
            check-strictly
            :render-after-expand="false"
            clearable
            filterable
            :filter-method="filterNode"
            class="parent-tree-select"
            value-key="id"
          >
            <template #default="{ node, data }">
              <div class="custom-tree-select-node">
                <span class="node-title">{{ node.label }}</span>
                <span class="node-path" v-if="data.parentPath">{{ data.parentPath }}</span>
              </div>
            </template>
          </el-tree-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleCreate">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </main>
</template>

<script>
import { getCategoryList, saveCategory, getNumList } from '@/api/article'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'

export default {
  name: 'LearningPage',
  data() {
    return {
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'title',
        value: 'id'
      },
      dialogVisible: false,
      newLibrary: {
        title: '',
        parentId: null
      },
      rules: {
        title: [
          { required: true, message: '请输入卡片库名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        parentId: [
          { required: false, message: '请选择父级节点', trigger: 'change' }
        ]
      },
      isMobile: false
    }
  },
  created() {
    this.fetchCategoryList()
    this.checkMobile()
    window.addEventListener('resize', this.checkMobile)
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.checkMobile)
  },
  methods: {
    checkMobile() {
      this.isMobile = window.innerWidth <= 768
    },
    // 获取卡片库列表
    async fetchCategoryList() {
      try {
        const response = await getCategoryList()
        if (response.status === 200 && response.data?.data) {
          // 转换接口返回的数据格式为树形结构，并添加父级路径信息
          this.treeData = this.processTreeData(response.data.data)
          // 获取每个节点的统计数据
          await this.fetchNodeStats()
        } else {
          ElMessage.error('获取卡片库列表失败: 数据格式错误')
        }
      } catch (error) {
        console.error('获取卡片库列表出错:', error)
        ElMessage.error('获取卡片库列表失败')
      }
    },

    async fetchNodeStats() {
      try {
        const response = await getNumList()
        if (response.status === 200 && response.data?.data) {
          // 更新树节点的统计数据
          this.updateNodeStats(this.treeData, response.data.data)
        }
      } catch (error) {
        console.error('获取统计数据失败:', error)
      }
    },

    updateNodeStats(nodes, stats) {
      nodes.forEach(node => {
        const nodeStats = stats.find(stat => stat.id === node.id)
        if (nodeStats) {
          node.newCards = nodeStats.newNum
          node.toReview = nodeStats.readNum
          node.studiedPercentage = nodeStats.avgReadNum.toFixed(1)
        }
        if (node.children && node.children.length > 0) {
          this.updateNodeStats(node.children, stats)
        }
      })
    },

    processTreeData(data, parentPath = '') {
      return data.map(item => {
        const currentPath = parentPath ? `${parentPath} / ${item.name}` : item.name
        return {
          id: item.id,
          title: item.name,
          parentPath: parentPath,
          newCards: 0,
          toReview: 0,
          studiedPercentage: '0.0',
          progressFraction: '0/0',
          progressWidth: '0%',
          createTime: item.createTime,
          updateTime: item.updateTime,
          children: item.children ? this.processTreeData(item.children, currentPath) : []
        }
      })
    },

    filterNode(value, data) {
      if (!value) return true
      return data.title.toLowerCase().includes(value.toLowerCase()) ||
             (data.parentPath && data.parentPath.toLowerCase().includes(value.toLowerCase()))
    },

    showCreateDialog() {
      this.dialogVisible = true
      this.newLibrary = {
        title: '',
        parentId: null
      }
    },

    async handleCreate() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            const response = await saveCategory({
              name: this.newLibrary.title,
              pid: this.newLibrary.parentId || 0
            })

            if (response.status === 200) {
              ElMessage({
                type: 'success',
                message: '新建卡片库成功'
              })
              
              // 重新获取列表
              await this.fetchCategoryList()
              
              this.dialogVisible = false
            } else {
              ElMessage.error(response.data?.message || '新建卡片库失败')
            }
          } catch (error) {
            console.error('新建卡片库出错:', error)
            ElMessage.error('新建卡片库失败')
          }
        }
      })
    },

    handleNodeClick(data, node) {
      if (data.children && data.children.length > 0) {
        node.expanded = !node.expanded
        return
      }

      this.$emit('select-card', {
        title: data.title,
        id: data.id,
        newCards: data.newCards,
        toReview: data.toReview,
        studiedPercentage: data.studiedPercentage,
        progressFraction: data.progressFraction,
        progressWidth: data.progressWidth
      })
    },

    calculateNodeStats(node, statType) {
      if (!node.children || node.children.length === 0) {
        return node[statType] || 0
      }

      let total = 0
      const calculateTotal = (nodes) => {
        nodes.forEach(child => {
          if (!child.children || child.children.length === 0) {
            if (statType === 'studiedPercentage') {
              total += parseFloat(child[statType] || 0)
            } else {
              total += parseInt(child[statType] || 0)
            }
          } else {
            calculateTotal(child.children)
          }
        })
      }

      calculateTotal(node.children)

      if (statType === 'studiedPercentage') {
        const leafCount = this.countLeafNodes(node)
        return leafCount > 0 ? (total / leafCount).toFixed(1) : '0.0'
      }

      return total
    },

    countLeafNodes(node) {
      if (!node.children || node.children.length === 0) {
        return 1
      }
      return node.children.reduce((total, child) => total + this.countLeafNodes(child), 0)
    },

    renderLabel(node) {
      if (!node) return ''
    }
  }
}
</script>

<style scoped>
.learning-page {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
background-color: #f0f2f5;
display: flex;
flex-direction: column;
height: 100vh;
}

.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px;
background-color: #fff;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.time {
font-size: 18px;
font-weight: bold;
}

.title-bar {
display: flex;
gap: 20px;
}

.title {
font-size: 18px;
color: #888;
position: relative;
}

.title.active {
color: #000;
font-weight: bold;
}

.title.active::after {
content: '';
position: absolute;
left: 0;
bottom: -5px;
width: 100%;
height: 2px;
background-color: #007bff; /* Placeholder color */
}

.header-icons {
display: flex;
align-items: center;
gap: 15px;
}

.vip {
font-size: 12px;
color: #f7b500; /* Placeholder color */
border: 1px solid #f7b500;
padding: 2px 5px;
border-radius: 3px;
}

.icon {
font-size: 20px;
}

.content {
flex-grow: 1;
padding: 16px;
overflow-y: auto;
max-width: 1200px;
margin: 0 auto;
}

.section {
background-color: #fff;
padding: 20px;
margin-bottom: 16px;
border-radius: 12px;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.section h2 {
font-size: 1.25rem;
margin-top: 0;
margin-bottom: 15px;
color: #1a1a1a;
font-weight: 600;
}

.study-summary {
display: flex;
justify-content: space-around;
text-align: center;
padding: 16px 0;
background: #f8f9fa;
border-radius: 8px;
}

.summary-item {
flex: 1;
padding: 0 12px;
}

.summary-item .number {
font-size: 1.5rem;
font-weight: 600;
color: #1a1a1a;
margin-bottom: 4px;
}

.summary-item .label {
font-size: 0.875rem;
color: #666;
}

.learning-content h2 {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.learning-content h2::after {
  content: '卡牌资源 >';
  font-size: 12px;
  color: #007bff; /* Placeholder color */
  font-weight: normal;
}

.learning-item {
background-color: #fff;
padding: 24px;
margin-bottom: 16px;
border-radius: 12px;
border: 1px solid #ebeef5;
transition: all 0.3s ease;
cursor: pointer;
position: relative;
overflow: hidden;
}

.learning-item:hover {
transform: translateY(-2px);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
border-color: #409EFF;
}

.item-header {
margin-bottom: 16px;
}

.item-title-wrapper {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
}

.item-title {
font-size: 1.2rem;
font-weight: 600;
color: #1a1a1a;
}

.item-date {
font-size: 0.9rem;
color: #909399;
background: #f5f7fa;
padding: 4px 8px;
border-radius: 4px;
}

.item-stats {
display: flex;
gap: 24px;
}

.stat-item {
display: flex;
flex-direction: column;
gap: 4px;
}

.stat-label {
font-size: 0.85rem;
color: #909399;
}

.stat-value {
font-size: 1.1rem;
font-weight: 600;
color: #1a1a1a;
}

.progress-container {
width: 100%;
height: 6px;
background-color: #f5f7fa;
border-radius: 3px;
overflow: hidden;
margin: 12px 0;
}

.progress-bar {
height: 100%;
background: linear-gradient(90deg, #409EFF 0%, #36cfc9 100%);
border-radius: 3px;
transition: width 0.3s ease;
}

.progress-text {
font-size: 0.9rem;
color: #909399;
text-align: right;
}

.footer-nav {
display: flex;
justify-content: space-around;
padding: 10px 0;
background-color: #fff;
box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.05);
}

.nav-item {
display: flex;
flex-direction: column;
align-items: center;
font-size: 12px;
color: #888;
}

.nav-item .icon {
  font-size: 24px;
}

.nav-item.add-button {
  background-color: #007bff; /* Placeholder color */
  color: #fff;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  justify-content: center;
  font-size: 30px;
  margin-top: -10px;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
}

.nav-item.add-button .icon {
   font-size: 30px;
}

.section-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 24px;
padding-bottom: 16px;
border-bottom: 1px solid #ebeef5;
}

.title-wrapper {
display: flex;
flex-direction: column;
gap: 4px;
}

.title-wrapper h2 {
margin: 0;
font-size: 1.5rem;
font-weight: 600;
color: #1a1a1a;
line-height: 1.4;
}

.subtitle {
font-size: 0.9rem;
color: #909399;
}

.create-button {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 20px;
font-weight: 500;
border-radius: 8px;
transition: all 0.3s ease;
background: linear-gradient(135deg, #409EFF 0%, #36cfc9 100%);
border: none;
}

.create-button:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.button-text {
display: inline-block;
}

.dialog-footer {
  text-align: right;
  padding-top: 20px;
}

.el-dialog__body {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-input-number {
  width: 180px;
}

.create-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.create-dialog :deep(.el-form-item__label) {
  font-weight: 500;
}

@media (max-width: 768px) {
  .content {
    padding: 12px;
  }

  .section {
    padding: 16px;
    margin-bottom: 12px;
    border-radius: 8px;
  }

  .section-header {
    margin-bottom: 20px;
    padding-bottom: 12px;
  }

  .title-wrapper h2 {
    font-size: 1.3rem;
  }

  .subtitle {
    font-size: 0.85rem;
  }

  .create-button {
    padding: 8px 16px;
  }

  .button-text {
    display: none;
  }

  .study-summary {
    padding: 12px 0;
  }

  .summary-item {
    padding: 0 8px;
  }

  .summary-item .number {
    font-size: 1.25rem;
  }

  .summary-item .label {
    font-size: 0.75rem;
  }

  .learning-item {
    padding: 16px;
  }

  .item-title {
    font-size: 1.1rem;
  }

  .item-date {
    font-size: 0.85rem;
  }

  .item-stats {
    gap: 16px;
  }

  .stat-value {
    font-size: 1rem;
  }

  .create-dialog {
    width: 95% !important;
  }

  .create-dialog :deep(.el-dialog__body) {
    padding: 16px;
  }

  .create-dialog :deep(.el-form-item__label) {
    float: none;
    display: block;
    text-align: left;
    padding: 0 0 8px;
  }

  .create-dialog :deep(.el-form-item__content) {
    margin-left: 0 !important;
  }
}

@media (max-width: 480px) {
  .content {
    padding: 8px;
  }

  .section {
    padding: 12px;
  }

  .study-summary {
    flex-direction: column;
    gap: 12px;
  }

  .summary-item {
    padding: 8px 0;
    border-bottom: 1px solid #ebeef5;
  }

  .summary-item:last-child {
    border-bottom: none;
  }

  .item-stats {
    flex-wrap: wrap;
    gap: 12px;
  }

  .stat-item {
    flex: 1;
    min-width: 80px;
  }
}

.learning-tree {
  background-color: #fff;
  border-radius: 12px;
  padding: 16px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  width: 100%;
}

.node-title {
  font-weight: 600;
  color: #1a1a1a;
}

.node-stats {
  display: flex;
  gap: 24px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.stat-label {
  font-size: 0.85rem;
  color: #909399;
}

.stat-value {
  font-size: 1.1rem;
  font-weight: 600;
  color: #1a1a1a;
}

:deep(.el-tree-node__content) {
  height: auto;
  padding: 12px 0;
}

:deep(.el-tree-node__content:hover) {
  background-color: #f5f7fa;
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #ecf5ff;
}

@media (max-width: 768px) {
  .node-stats {
    gap: 16px;
  }

  .stat-value {
    font-size: 1rem;
  }

  .custom-tree-node {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .node-stats {
    width: 100%;
    justify-content: space-between;
  }
}

.create-dialog :deep(.el-tree-select) {
  width: 100%;
}

.create-dialog :deep(.el-tree-select .el-input__wrapper) {
  padding: 0 8px;
}

.create-dialog :deep(.el-tree-select .el-input__inner) {
  height: 32px;
  line-height: 32px;
}

.parent-tree-select {
  width: 100%;
}

.custom-tree-select-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 4px 0;
}

.node-title {
  font-weight: 500;
  color: #1a1a1a;
}

.node-path {
  font-size: 12px;
  color: #909399;
  margin-left: 8px;
}

:deep(.el-tree-select .el-input__wrapper) {
  padding: 0 8px;
}

:deep(.el-tree-select .el-input__inner) {
  height: 32px;
  line-height: 32px;
}

:deep(.el-tree-select-dropdown__item) {
  padding: 0 12px;
}

:deep(.el-tree-select-dropdown__item.selected) {
  background-color: #f5f7fa;
}

:deep(.el-tree-select-dropdown__item:hover) {
  background-color: #f5f7fa;
}

@media (max-width: 768px) {
  .custom-tree-select-node {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .node-path {
    margin-left: 0;
  }
}
</style> 